import { Singleton } from "../../meshTools/Singleton";
import { GameMgr } from "./GameMgr";


interface IEventData
{
    cb: Function;
    target: any
}

interface IEvent
{
    [eventName: string]: IEventData[]
}

export class EventCenter extends Singleton
{
    private _handle: IEvent = {} as IEvent;
    
    public AddEventListener (eventName: string | number, cb: Function, target?: any): void
    {
        GameMgr.Console.Log('添加监听：'+eventName);
        eventName = eventName.toString();
        if (!this._handle[eventName])
        {
            this._handle[eventName] = [];
        }

        let eventData: IEventData = {} as IEventData;
        eventData.cb = cb;
        eventData.target = target;
        this._handle[eventName].push(eventData);
    }

    public RemoveEventListener (eventName: string | number, cb: Function, target?: any): void
    {
        GameMgr.Console.Log('移除监听：'+eventName);
        eventName = eventName.toString();
        let list: IEventData[] = this._handle[eventName] ?? [];
        if (list.length <= 0)
        {
            return;
        }

        for (let i = 0; i < list.length; ++i)
        {
            let event: IEventData = list[i];
            if (event.cb === cb && (!target || target === event.target))
            {
                list.splice(i, 1);
            }
        }
    }

    public Send (eventName: string | number, ...params: any): void
    {
        eventName = eventName.toString();
        let list: IEventData[] = this._handle[eventName] ?? [];
        if (list.length <= 0)
        {
            return;
        }

        for (let i = 0; i < list.length; ++i)
        {
            let event: IEventData = list[i];
            event.cb.apply(event.target, params);
        }
    }
}

//通知的消息类型
export enum EventType{
    ReceiveMessage = 'receiveMessage',//收到长链接消息的通知
    ReceiveErrorMessage = 'receiveErrorMessage',//收到长链接消息的通知,错误 code 的消息
    AutoMessage = 'autoMessage',// 程序内的通知
}







